<template>
  <a-modal visible="visible" title="新建督办任务" :width="1200" @ok="handleAddSubmit" @cancel="handleAddCancel">
    <!-- <pre>{{ options }}</pre> -->
    <a-form ref="addFormRef" :model="addForm" :rules="addFormRules" layout="vertical">
      <!-- 第一行 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督办来源" field="source" required>
            <a-select v-model="addForm.source" :options="options.source" placeholder="请选择督办来源" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="问题类型" field="problemType" required>
            <a-select
              v-model="addForm.problemType"
              :options="options.problemType"
              placeholder="请选择问题类型"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第二行 4列 -->
      <a-row :gutter="16" align="middle">
        <a-col :span="12">
          <a-form-item label="督察要求" field="requirements" required>
            <a-input v-model="addForm.requirements" placeholder="请输入督察要求" />
          </a-form-item>
        </a-col>
        <a-col :span="12" style="display: flex; align-items: center">
          <label style="margin-right: 10px; min-width: 70px">领导批示</label>
          <a-checkbox v-model="addForm.leaderInstruction" style="margin-right: 24px; white-space: nowrap"
            >批示</a-checkbox
          >
          <template v-if="addForm.leaderInstruction">
            <a-input
              v-model="addForm.leaderRemark"
              placeholder="请输入批示备注"
              style="width: 180px; margin-right: 24px"
            />
            <label style="margin-right: 8px; min-width: 70px">相关文件</label>
            <a-upload v-model:file-list="addForm.leaderFiles" action="/api/upload" :limit="3" style="width: 180px" />
          </template>
        </a-col>
      </a-row>
      <!-- 第三行 整改问题清单 -->
      <a-row :gutter="16">
        <a-col :span="24">
          <div style="margin-bottom: 16px; display: flex; align-items: center">
            <span style="font-weight: bold">整改问题清单</span>
            <a-button type="primary" size="mini" style="margin-left: 12px" @click="addProblemRow">
              <icon-plus />
              添加一条问题
            </a-button>
          </div>
          <a-table
            class="problem-table"
            :columns="problemColumns"
            :data="addForm.problemList"
            :pagination="false"
            row-key="index"
            bordered
            style="margin-bottom: 0"
          >
            <template #problemDesc="{ record }">
              <a-textarea
                v-model="record.problemDesc"
                placeholder="请输入问题描述"
                :auto-size="{ minRows: 2, maxRows: 6 }"
              />
            </template>
            <template #action="{ rowIndex }">
              <a-button size="mini" status="danger" @click="removeProblemRow(rowIndex)"> 删除 </a-button>
            </template>
          </a-table>
        </a-col>
      </a-row>
      <!-- 第四行 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改人员" field="rectificationUsers" required>
            <a-tree-select
              v-model="addForm.rectificationUsers"
              :data="userTreeData"
              multiple
              :field-names="{ key: 'key', title: 'name', children: 'children' }"
              placeholder="请选择整改人员"
              allow-search
              allow-clear
              :default-expand-selected="false"
              :default-expand-all="false"
              :filter-tree-node="filterUserName"
              @change="handleRectificationUsersChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="整改单位" field="rectificationUnits">
            <a-input v-model="addForm.rectificationUnits" disabled placeholder="自动填充整改单位" />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第五行 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改期限" field="rfDateRange" required>
            <a-range-picker v-model="addForm.rfDateRange" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="审核人" field="auditor" required>
            <a-tree-select
              v-model="addForm.auditor"
              :data="auditorTreeData"
              :field-names="{ key: 'key', title: 'name', children: 'children' }"
              placeholder="请选择审核人"
              allow-search
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第六行 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="备注" field="remark">
            <a-input v-model="addForm.remark" placeholder="请输入备注" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="相关附件" field="attachments">
            <a-upload v-model:file-list="addForm.attachments" action="/api/upload" :limit="5" />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第七行 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="填报单位" field="reportDeptId">
            <a-input v-model="addForm.reportDeptName" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="填报人" field="reportUserId">
            <a-input v-model="addForm.reportUser" disabled />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { createTask } from '@/api/task';
  import { useUserStore } from '@/store';
  import { IconPlus } from '@arco-design/web-vue/es/icon';
  import { getUserList, queryUserByTask, queryAuditorByTask } from '@/api/user';
  const props = defineProps({
    visible: Boolean,
    options: {
      type: Object,
      default: () => ({
        source: [],
        problemType: [],
        rectificationUnit: [],
        feedbackUnit: [],
        status: []
      })
    },
    form: Object
  });
  const emits = defineEmits(['update:visible', 'refresh']);

  const addFormRef = ref();
  const addForm = ref({});
  watch(
    () => props.form,
    val => {
      if (val) addForm.value = JSON.parse(JSON.stringify(val));
    },
    { immediate: true, deep: true }
  );
  const problemColumns = [
    { title: '序号', dataIndex: 'index', width: 60 },
    { title: '问题描述', dataIndex: 'problemDesc', slotName: 'problemDesc' },
    { title: '操作', dataIndex: 'action', width: 60, slotName: 'action' }
  ];
  const userTreeData = ref([]);
  const auditorTreeData = ref([]);
  const expandedKeys = ref([]); // 强制控制展开项
  function onDropdownVisibleChange(visible) {
    if (visible) {
      expandedKeys.value = [];
    }
  }

  const addFormRules = {
    source: [{ required: true, message: '请选择督办来源' }],
    problemType: [{ required: true, message: '请选择问题类型' }],
    requirements: [{ required: true, message: '请输入督察要求' }],
    rectificationUsers: [{ required: true, message: '请选择整改人员' }],
    rfDateRange: [{ required: true, message: '请选择整改期限' }],
    auditor: [{ required: true, message: '请选择审核人' }]
  };

  function addProblemRow() {
    addForm.value.problemList.push({ index: addForm.value.problemList.length + 1, problemDesc: '' });
  }
  function removeProblemRow(idx) {
    addForm.value.problemList.splice(idx, 1);
    addForm.value.problemList.forEach((item, i) => (item.index = i + 1));
  }

  async function fetchUserTreeData() {
    try {
      const res = await queryUserByTask();
      const tree = [];
      if (res && res.data) {
        Object.entries(res.data).forEach(([groupId, userList]) => {
          if (userList.length > 0) {
            // 按部门分组用户
            const deptMap = new Map();
            userList.forEach(user => {
              const deptName = user.deptName || '未分配部门';
              if (!deptMap.has(deptName)) {
                deptMap.set(deptName, []);
              }
              deptMap.get(deptName).push(user);
            });

            // 构建树形结构：组织 -> 部门 -> 用户
            const deptChildren = [];
            deptMap.forEach((users, deptName) => {
              deptChildren.push({
                key: `dept_${groupId}_${deptName}`,
                name: deptName,
                selectable: false,
                children: users.map(user => ({
                  key: user.userId,
                  name: user.name
                }))
              });
            });

            tree.push({
              key: `group_${groupId}`,
              userId: Number(groupId),
              name: userList[0].groupName,
              selectable: false,
              children: deptChildren
            });
          }
        });
      }
      userTreeData.value = tree;
    } catch (e) {
      Message.error('获取整改人员失败');
    }
  }

  async function fetchAuditorTreeData() {
    try {
      const res = await queryAuditorByTask();
      const tree = [];
      if (res && res.data) {
        Object.entries(res.data).forEach(([groupId, userList]) => {
          if (userList.length > 0) {
            tree.push({
              key: `group_${groupId}`,
              userId: Number(groupId),
              name: userList[0].groupName,
              selectable: false,
              children: userList.map(user => ({
                key: user.userId,
                name: user.name + '-' + (user.deptName || '')
              }))
            });
          }
        });
      }
      auditorTreeData.value = tree;
    } catch (e) {
      Message.error('获取审核人失败');
    }
  }

  function handleAddCancel() {
    emits('update:visible', false);
    // 重置表单数据
    Object.keys(addForm.value).forEach(key => {
      if (key === 'problemList') {
        addForm.value[key] = [{ index: 1, problemDesc: '' }];
      } else if (Array.isArray(addForm.value[key])) {
        addForm.value[key] = [];
      } else {
        addForm.value[key] = '';
      }
    });
  }
  function handleAddSubmit() {
    addFormRef.value.validate().then(async () => {
      try {
        const payload = { ...addForm.value };
        payload.reportDept = payload.reportDeptId;
        payload.reportUser = payload.reportUserId;

        // 处理整改人员：数组转字符串
        if (Array.isArray(payload.rectificationUsers)) {
          payload.rfUsers = payload.rectificationUsers.join(',');
        } else {
          payload.rfUsers = '';
        }

        // 处理整改单位：根据整改人员计算单位ID
        if (Array.isArray(payload.rectificationUsers) && payload.rectificationUsers.length > 0) {
          const userGroupMap = new Map();
          userTreeData.value.forEach(group => {
            group.children.forEach(dept => {
              dept.children.forEach(user => {
                userGroupMap.set(user.key, {
                  userId: user.key,
                  groupId: group.userId,
                  groupName: group.name,
                  userName: user.name
                });
              });
            });
          });

          const selectedGroups = new Set();
          payload.rectificationUsers.forEach(userId => {
            const userInfo = userGroupMap.get(userId);
            if (userInfo) {
              selectedGroups.add(userInfo.groupId);
            }
          });

          payload.rfUnits = Array.from(selectedGroups).join(',');
        } else {
          payload.rfUnits = '';
        }

        if (Array.isArray(payload.rfDateRange) && payload.rfDateRange.length === 2) {
          const [start, end] = payload.rfDateRange;
          payload.rfStartDate = start ? new Date(start).getTime() : '';
          payload.rfEndDate = end ? new Date(end).getTime() : '';
        }
        delete payload.rfDateRange;
        delete payload.rectificationUsers;
        delete payload.rectificationUnits;

        if (payload.attachments && payload.attachments.length) {
          payload.attachments = payload.attachments.map(f => f.url || f.response?.url || f);
        }
        await createTask(payload);
        Message.success('提交成功');

        // 先触发刷新事件，再关闭弹窗
        emits('refresh');

        // 延迟关闭弹窗，确保刷新事件先被处理
        setTimeout(() => {
          emits('update:visible', false);
        }, 100);
      } catch (e) {
        Message.error('提交失败');
      }
    });
  }

  watch(
    () => addForm.value.leaderInstruction,
    val => {
      if (!val) {
        addForm.value.leaderRemark = '';
        addForm.value.leaderFiles = [];
      }
    }
  );

  addForm.value.leaderInstruction = false;

  function handleRectificationUsersChange(value) {
    const userGroupMap = new Map();
    userTreeData.value.forEach(group => {
      group.children.forEach(dept => {
        dept.children.forEach(user => {
          userGroupMap.set(user.key, {
            userId: user.key,
            groupId: group.userId,
            groupName: group.name,
            deptName: dept.name,
            userName: user.name
          });
        });
      });
    });
    const selectedGroups = new Map();
    const selectedUserKeys = value;
    selectedUserKeys.forEach(userKey => {
      const userInfo = userGroupMap.get(userKey);
      if (userInfo) {
        if (selectedGroups.has(userInfo.groupId)) {
          Message.error('一个组织只能有一个整改接收人');
          const newValue = value.filter(key => key !== userKey);
          addForm.value.rectificationUsers = newValue;
          return;
        }
        selectedGroups.set(userInfo.groupId, userInfo.groupName);
      }
    });
    addForm.value.rectificationUnits = Array.from(selectedGroups.values()).join(', ');
  }

  function filterUserName(searchValue, node) {
    // 只对叶子节点（用户）进行搜索，且只用 name 字段
    return !node.children && node.name && node.name.includes(searchValue);
  }

  onMounted(() => {
    fetchUserTreeData();
    fetchAuditorTreeData();
  });
</script>
